<template>
  <!-- <page-meta> </page-meta> -->
  <div class="content">
    <div v-if="!isBaseVersion">
      <div class="div_title">
        <span class="title" ref="guide8">开账操作</span>
        <el-button @click="onBackPre" v-if="openAccountStep == 1">重新选择开账方式</el-button>
      </div>
      <el-divider></el-divider>
      <div class="originView" v-if="openAccountStep == 0 || openAccountStep == 3">
        <span class="subtitle">您好，为了保证账套数据的严谨性，在使用软件之前，请选择您的开账方式</span>
        <div class="originContent">
          <div class="originItem">
            <div class="itemBack" @click="clickInitialInformartion">
              <span>
                先录入期初信息
                <br />再开单
              </span>
            </div>
            <span class="itemTip">
              注：先录入或导入期初库存和期初应收应
              <br />付、期初账户余额数据，再进行开单、数据操作使用更加规范。
            </span>
          </div>
          <div class="originItem">
            <div class="itemBack" style="background-color: #fd6c21" @click="clickDirectOrder">
              <span>
                直接开单
                <br />不录入期初
              </span>
            </div>
            <span class="itemTip">
              先开单，后期通过调整单的方式，进行库
              <br />存和应收应付数据的调整。
            </span>
          </div>
        </div>
      </div>
      <div v-else>
        <div class="step_view">
          <span class="step_title">请点击图标进行期初录入，如无期初可以直接开始使用</span>
          <div class="step_content">
            <div class="step_item" @click="clickInitialInventory">
              <div class="img_view" :style="{ 'background-color': openingInventory.enter_opening_inventory == 1 ? '#1993FB' : '#CBCED3' }">
                <img style="width: 55px; height: 54px" src="@/assets/step1/step1.png" mode="aspectFill" />
              </div>
              <div class="item_title" :style="{ color: openingInventory.enter_opening_inventory == 1 ? '#1993FB' : '#666666' }">期初库存录入</div>
              <span>
                包含商品信息、仓库
                <br />库存信息
              </span>
            </div>
            <!-- <img class="arrow_view"
              :src="openAccountStep > 1 ? require('@/assets/step1/3f77ff53-ff28-4c9d-b817-8f2333677b6d.png') : require('@/assets/step1/0771713c-8ba9-4f0f-92ea-2f69138ff01e.png')"
              mode="aspectFill" /> -->
            <div class="step_item" @click="initialPayment">
              <div class="img_view" :style="{ 'background-color': openingInventory.enter_opening_collection_and_pay == 1 ? '#1993FB' : '#CBCED3' }">
                <img style="width: 55px; height: 54px" src="@/assets/step1/step2.png" mode="aspectFill" />
              </div>
              <div class="item_title" :style="{ color: openingInventory.enter_opening_collection_and_pay == 1 ? '#1993FB' : '#666666' }">
                期初应收应付录入
              </div>
              <span>
                包含往来单位(供应商、客户)、物流信息
                <br />期初应收应付信息
              </span>
            </div>
            <!-- <img class="arrow_view"
              :src="openAccountStep > 2 ? require('@/assets/step1/3f77ff53-ff28-4c9d-b817-8f2333677b6d.png') : require('@/assets/step1/0771713c-8ba9-4f0f-92ea-2f69138ff01e.png')"
              mode="aspectFill" /> -->
            <div class="step_item" @click="balance">
              <div class="img_view" :style="{ 'background-color': openingInventory.enter_opening_bank_balance == 1 ? '#1993FB' : '#CBCED3' }">
                <img style="width: 55px; height: 54px" src="@/assets/step1/step3.png" mode="aspectFill" />
              </div>
              <div class="item_title" :style="{ color: openingInventory.enter_opening_bank_balance == 1 ? '#1993FB' : '#666666' }">
                期初账户余额录入
              </div>
              <span>
                包含各账户期初
                <br />余额信息
              </span>
            </div>
            <!-- <img class="arrow_view"
              :src="openAccountStep > 3 ? require('@/assets/step1/3f77ff53-ff28-4c9d-b817-8f2333677b6d.png') : require('@/assets/step1/5bbea7e6-6d39-4890-abfd-063eacd2cf64.png')"
              mode="aspectFill" /> -->
            <div class="step_item" @click="clickBeginUse">
              <div class="img_view" :style="{ 'background-color': '#20C9AC' }">
                <img style="width: 55px; height: 54px" src="@/assets/step1/step4.png" mode="aspectFill" />
              </div>
              <div class="item_title" :style="{ color: '#20C9AC' }">开始使用</div>
              <span>
                期初录入完毕
                <br />开单后不可修改
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-else class="base-version-form">
      <div class="create-title">选择使用日期</div>
      <el-form ref="form" :model="form" label-width="80px" class="form-view">
        <el-form-item label="公司名称" prop="companyName">
          <el-input :disabled="true" v-model="form.companyName"></el-input>
        </el-form-item>
        <el-form-item label="启用时间" prop="enableDate">
          <el-date-picker
            type="date"
            placeholder="启用时间"
            v-model="form.enableDate"
            style="width: 100%"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="币种符号" prop="currencyType">
          <j-dict-select-tag
            type="select"
            dictCode="currency_type"
            style="width: 100%"
            v-model="form.currencyType"
            placeholder="请选择币种符号"
          ></j-dict-select-tag>
        </el-form-item>
        <div class="dialog-footer">
          <el-button type="primary" class="btn" @click="onSubmit">开 账</el-button>
        </div>
      </el-form>
    </div>
    <!-- 提醒弹框 -->
    <DialogSimplePrompt ref="simplePrompt" @onSure="onSureSimple"></DialogSimplePrompt>
    <!-- 开账提醒弹窗 -->
    <DialogSelectBillingMethod ref="selectBillingMethod" @onSure="onSureBillingMethod"></DialogSelectBillingMethod>
    <!-- 创建账套时间 -->
    <DialogCreateCard ref="createCardDialog" @onSubmit="onSureCreateCard"></DialogCreateCard>
  </div>
</template>

<script>
import DialogSimplePrompt from '../components/dialogSimplePrompt'
import DialogSelectBillingMethod from '../components/dialogSelectBillingMethod'
import DialogCreateCard from '../components/dialogCreateCard'
import { getAction, postAction } from '@/api/manage'
import { handleIsBaseVersion } from '@/utils'
import Vue from 'vue'
import { ACCOUNT_BOOK } from '@/store/mutation-types'
import { getTimeYMD } from '@/utils/DateFormatter'
import JDictSelectTag from '../../components/dict/JDictSelectTag.vue'

export default {
  name: 'SystemConfiguration',
  inject: ['closeAccountCurrent', 'closeAll'],
  components: {
    DialogSimplePrompt,
    DialogSelectBillingMethod,
    DialogCreateCard,
    JDictSelectTag
  },
  computed: {
    isBaseVersion() {
      return handleIsBaseVersion()
    }
  },
  data() {
    return {
      openAccountStep: 0, // 开账状态：0-初始状态 1-录入期初开账 2-不录入期初直接开账 3-已开账
      openingInventory: {
        enter_opening_inventory: 0,
        enter_opening_collection_and_pay: 0,
        enter_opening_bank_balance: 0,
      },
      form: {
        companyName: '',
        enableDate: '',
        currencyType: '1',
      }
    }
  },
  created() {
    this.openAccountStep = this.$store.getters.openAccountValue
    if (this.isBaseVersion) {
      let accountInfo = Vue.ls.get(ACCOUNT_BOOK) || {}
      this.form.companyName = accountInfo.companyName
      this.form.enableDate = getTimeYMD()
    }
  },
  watch: {
    $route: {
      immediate: true,
      handler() {
        if (this.$route.name == 'business-SystemConfiguration') {
          this.getOpenAccountFlag()
          // 获取录入数据标记
          this.getEnterDataMarkers()
        }
      },
    },
    '$store.getters.openAccountValue'(val) {
      this.openAccountStep = val
    },
  },
  mounted() {
    // 监听接收消息
    const that = this
    this.$EventBus.$on('getGuideItem', function (res) {
      if (res == 10) {
        let rect = that.$refs.guide8.getBoundingClientRect()
        let params = {
          rect,
          step: res,
        }
        this.$EventBus.$emit('showNoviceGuide', params)
      }
    })
  },
  beforeDestroy() {
    this.$EventBus.$off('getGuideItem')
  },
  methods: {
    clickInitialInformartion() {
      console.log('录入期初信息')
      if (this.openAccountStep == 3) {
        return this.$elMessage.warning('已经开账,无需操作!')
      }
      // 先录入期初信息再开单
      this.setOpenAccountType(1)
    },
    clickDirectOrder() {
      if (this.openAccountStep == 3) {
        return this.$elMessage.warning('已经开账,无需操作!')
      }
      console.log('直接开单')
      // 直接开单
      this.$refs.createCardDialog.show(true)
    },
    clickInitialInventory() {
      console.log('录入期初库存')
      this.$router.push({ path: '/baseInfomation/beginningOfPeriod/inventoryEntry' })
    },
    // 添加账套下系统配置-开账标志
    addOpenAccountFlag(flag) {
      let data = {
        flag,
      }
      getAction('/sysConfig/systemConfig/setOpenAccountStep', data).then((res) => {
        if (res.code === 200) {
          this.$store.commit('SET_OPEN_ACCOUNT_VALUE', flag)
          this.openAccountStep = flag
          if (flag === 3) {
            this.closeAll()
            return
          }
          this.getOpenAccountFlag()
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
    setOpenAccountType(openAccountType) {
      let data = {
        openAccountType, // 开账状态：1-录入期初开账 2-不录入期初直接开账
      }
      getAction('/openAccount/setOpenAccountType', data).then((res) => {
        if (res.code === 200) {
          this.$store.commit('SET_OPEN_ACCOUNT_VALUE', openAccountType)
          this.openAccountStep = openAccountType
          if (openAccountType === 3) {
            this.closeAll()
            return
          }
          this.getOpenAccountFlag()
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
    openAccount(enableDate) {
      let data = {
        // 开账状态：1-录入期初开账 2-不录入期初直接开账
        openAccountType: this.openAccountStep === 0 ? '2' : '1', 
        enableDate,
      }
      getAction('/openAccount/openAccount', data).then((res) => {
        if (res.code === 200) {
          this.$store.commit('SET_OPEN_ACCOUNT_VALUE', 3)
          this.closeAll()
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
    // 返回上一级
    reopenAccount(flag) {
      this.$refs.selectBillingMethod.hide()
      let data = {
        dataExistFlag: flag, // -1-不保留 1-保留
      }
      getAction('/openAccount/reopenAccount', data).then((res) => {
        if (res.code === 200) {
          this.$store.commit('SET_OPEN_ACCOUNT_VALUE', 0)
          this.closeAll()
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
    initialPayment() {
      console.log('录入期初应收应付')
      // if (this.openAccountStep >= 2) {
      this.$router.push({ path: '/baseInfomation/beginningOfPeriod/arAndapEntry' })
      // } else {
      //   this.$elMessage.warning('请先录入期初库存!')
      // }
    },
    balance() {
      // if (this.openAccountStep >= 3) {
      this.$router.push({ path: '/baseInfomation/beginningOfPeriod/accountBalanceEntry' })
      // } else {
      //   this.$elMessage.warning('请先录入期初库存和期初应收应付!')
      // }
      console.log('期初账户余额录入')
    },
    clickBeginUse() {
      console.log('开始使用')
      if (this.openAccountStep === 3) {
        this.$elMessage.warning('已经开账,无需操作!')
      } else {
        this.$refs.createCardDialog.show()
      }
    },
    // 获取期初信息
    getOpenAccountFlag() {
      getAction('/openAccount/getOpenAccountType', {}).then((res) => {
        if (res.code === 200) {
          // 开账状态：0-初始状态 1-录入期初开账 2-不录入期初直接开账 3-已开账
          if (!res.result) {
            this.openAccountStep = 0
          } else {
            this.openAccountStep = Number(res.result.value)
          }
          this.$store.commit('SET_OPEN_ACCOUNT_VALUE', this.openAccountStep)
        }
      })
    },
    // 获取录入数据标记
    getEnterDataMarkers() {
      getAction('/openAccount/getEnterDataMarkers', {}).then((res) => {
        if (res.code === 200) {
          let data = res.result
          // 设置默认值
          this.openingInventory =  this.$options.data().openingInventory
          data.forEach(item => {
            this.openingInventory[item.code] = item.value
          });
        }
      })
    },
    // 返回上一级
    onBackPre() {
      this.$refs.selectBillingMethod.show()
    },
    onSureSimple() {
      switch (this.simpleMark) {
        case 'directOrder':
          // 直接开单
          this.addOpenAccountFlag(0)
          break
        case 'beginUse':
          // 开始使用
          // this.openAccount()
          break
        case 'backPre':
          this.reopenAccount(-1)
          break
      }
    },
    onSureBillingMethod(val) {
      if (val === '-1') {
        this.onShowTipsDialog('已录入的基本信息数据将被清除', 'backPre')
      } else {
        this.reopenAccount(this.openAccountStep)
      }
    },
    onSureCreateCard(val) {
      // 开始使用
      //  this.openAccount(val + ' 00:00:00')
      // 开账状态：1-录入期初开账 2-不录入期初直接开账
      // 直接开账
      this.openAccount(val + ' 00:00:00')
    },
    onShowTipsDialog(msg, mark) {
      this.simpleMark = mark
      this.$refs.simplePrompt.showTwoBtn('el-icon-warning', msg, '是', '否')
    },
    // 开账
    onSubmit() {
      if (this.form.enableDate == null) {
        return this.$elMessage.error('必须选择启用时间！')
      }
      if (!this.form.currencyType) {
        return this.$elMessage.error('请选择币种符号！')
      }
      this.openAccountInventory(this.form.enableDate + ' 00:00:00', 1)
    },
    // 开账-必用版
    openAccountInventory(enableDate, openAccountType) {
      // 1-录入期初开账 2-不录入期初直接开账
      getAction('/openAccount/openAccount', { enableDate, openAccountType }).then((res) => {
        if (res.code === 200) {
          this.$store.commit('SET_OPEN_ACCOUNT_VALUE', 3)
          this.$elMessage.success('开账成功！')
          this.closeAll()
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
  },
}
</script>
<style lang="scss" scoped>
page {
  background: #dcdee2;
}

.content {
  height: 100%;
  margin: 0 8px;
  padding: 40px 28px;
  background-color: #ffffff;
}

.title {
  font-size: 16px;
  font-family: PingFang SC;
  font-weight: 600;
  line-height: 22px;
  color: #1b94fb;
}

.originView {
  width: 100%;
  text-align: center;
  display: flex;
  align-items: center;
  flex-direction: column;
}

.subtitle {
  font-size: 20px;
  font-family: PingFang SC;
  font-weight: 600;
  line-height: 50px;
  color: #666666;
  width: 100%;
  text-align: center;
}

.originContent {
  width: 684px;
  display: flex;
  justify-content: space-between;
}

.originItem {
  width: 294px;
  margin-top: 45px;
  text-align: left;
}

.itemBack {
  width: 100%;
  height: 197px;
  background-color: #1993fb;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 20px;
  margin-bottom: 16px;
  text-align: center;

  span {
    font-size: 22px;
    font-family: PingFang SC;
    font-weight: 600;
    line-height: 36px;
    color: #ffffff;
  }
}

.itemTip {
  font-size: 16px;
  font-family: PingFang SC;
  font-weight: 400;
  line-height: 30px;
  color: #666666;
}

.step_view {
  width: 100%;
  text-align: center;
  display: flex;
  align-items: center;
  flex-direction: column;
}

.step_title {
  font-size: 20px;
  font-family: PingFang SC;
  font-weight: 600;
  line-height: 30px;
  color: #1993fb;
  margin-top: 50px;
}

.step_content {
  display: flex;
  margin-top: 100px;
}

.step_item {
  // width: 170px;
  // text-align: center;
  display: flex;
  align-items: center;
  flex-direction: column;
  margin: 18px;
}

.img_view {
  width: 131px;
  height: 131px;
  border-radius: 65.5px;
  margin: 0 10px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.item_title {
  font-size: 16px;
  font-family: PingFang SC;
  font-weight: 500;
  line-height: 28px;
  margin: 19px 0;
}

.arrow_view {
  width: 36px;
  height: 33px;
  margin: 50px 16px 0;
}

.div_title {
  display: flex;
  justify-content: space-between;

  .el-button {
    height: 33px;
    font-size: 12px;
    font-family: PingFang SC-Semibold, PingFang SC;
    font-weight: 600;
    color: #1b94fb;
    border: 1px solid #1993fb;
    padding: 0 9px;
  }
}

.base-version-form {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 40px;

  .create-title {
    font-size: 30px;
    font-weight: 500;
    color: #666666;
    margin-bottom: 20px;
  }

  .form-view {
    width: 360px;
  }

  .dialog-footer {
    display: flex;
    justify-content: center;
    margin-top: 30px;

    .btn {
      width: 100px;
      height: 40px;
      padding: 0;
    }
  }
}
</style>
